import React from "react"
import { useReducer } from "react"

export const ReducerDemo = () => {
  const initialPerson = {
    name: 'Tom',
    age: 28,
    gender: 'man'
  }
  const reduce = (state, action) => {
    const { type, payload } = action
    switch (type) {
      case 'incrementAge':
        return { ...state, age: state.age + 1 }
      case 'decrementAge':
        return { ...state, age: state.age - 1 }
      case 'changePerson':
        return { ...payload }

      default:
        return state
    }
  }

  const [state, dispatch] = useReducer(reduce, initialPerson)
  const { name, age, gender } = state
  return (
    <>
      <h2>useReducer的使用</h2>
      <h3>当前人员信息</h3>
      <span>name:{name}, age: {age}, gender:{gender}</span>
      <button onClick={() => dispatch({ type: 'incrementAge' })}>增加年龄</button>
      <button onClick={() => dispatch({ type: 'decrementAge' })}>减小年龄</button>
      <button onClick={() => dispatch({ type: 'changePerson', payload: { name: 'Mary', age: 18, gender: 'woman' } })}>换人</button>
    </>
  )
}